from random import randrange

from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
import re
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django import http
from django.template import loader
from django.urls import reverse
from django.views import View
import pandas as pd
import time
import json
import requests
import re
from django.core import serializers
from index.cht import *
from index import get_datas
from index.models import data_province, data_area, data_china
from index import getsql
from pyecharts.faker import Faker


# 最后更新时间

last_time = int(time.time())


class MainView(View):
    # last_time = 0
    # def __init__(self):
    #     self.last_time = int(time.time())
    def get(self, request):
        global last_time
        last_time = get_datas.get_datas(last_time)
        #print(111111)
        pro, are = data_province.objects.all(), data_area.objects.all()
        template = loader.get_template('home_page.html')
        mp = map_base(pro)
        # get_js_dependencies()
        context = dict(myechart=mp.render_embed())
        return HttpResponse(template.render(context, request))


class gt404(View):
    def get(self,request):
        return render(request,"404.html")

class MapView(View):
    def get(self, request):
        pro, are = data_province.objects.all(), data_area.objects.all()
        aa =[(i.name, i.total_confirm) for i in pro]
        data = {'data':china_map(aa)}
        return JsonResponse(data)

    def post(self, request):
        concat = request.POST
        postBody = request.body
        tp = json.loads(postBody)
        global last_time
        last_time = get_datas.get_datas(last_time)

        a = data_province.objects.all().order_by(tp['title'])
        p1,p2 = a.values_list('name'),a.values_list(tp['title'])
        p1 = [i[0] for i in p1]
        p2 = [i[0] for i in p2]
        aa,maxlen = [],len(p1)
        #慢
        for i in range(0,maxlen):
            aa.append([p1[i],p2[i]])
        #print(aa)
        data = {
            'code':200,
            'data':{
                'mp':china_map(aa,tp),
                'ba':china_bar(aa,tp),
                'pi':china_pie(aa,tp),
                'wc':china_wcd(aa,tp),
            },
            'msg':'OK',
        }
        return JsonResponse(data)



class history(View):
    def post(self,request):
        concat = request.POST
        postBody = request.body
        tp = json.loads(postBody)
        df = pd.read_sql('db_china_history',getsql.getengine())
        aa = df.to_dict(orient="dict")
        #print(df.keys())
        data = {
            'code':200,
            'msg':'OK',
            'data':{
                'ln1':china_line1(aa,tp),
                'ln2':china_line2(aa,tp),
            }
        }
        return JsonResponse(data)



class all(View):
    def post(self,request):
        global last_time
        last_time = get_datas.get_datas(last_time)
        are_list, are = data_area.objects.all().order_by("-total_confirm"),[]
        pro_list, pro= data_province.objects.all().order_by("-total_confirm"),[]
        cha_list, cha= data_china.objects.all(), []
        for obj in pro_list:
            pro.append(model_to_dict(obj))
        for obj in are_list:
            are.append(model_to_dict(obj))
        for obj in cha_list:
            cha.append(model_to_dict(obj))
        #print(pro)
        return http.JsonResponse({
            'code':200,
            'msg':'OK',
            'data':{
                'pro': pro,
                'are':are,
                'cha':cha,}})


class province(View):
    def get(self,request):
        global last_time
        last_time = get_datas.get_datas(last_time)
        pro_list, pro= data_province.objects.all(),[]
        for obj in pro_list:
            pro.append(model_to_dict(obj))
        #print(pro)
        return http.JsonResponse({
            'code':200,
            'msg':'OK',
            'pro': pro,})

    def post(self,request):
        global last_time
        last_time = get_datas.get_datas(last_time)
        pro_list, pro= data_province.objects.all().order_by("-total_confirm"),[]
        for obj in pro_list:
            pro.append(model_to_dict(obj))
        #print(pro)
        return http.JsonResponse({
            'code':200,
            'msg':'OK',
            'pro': pro,})

class area(View):
    def get(self,request,pname):
        count = data_area.objects.filter(count_id=pname).count()
        if count==0:
            return HttpResponse("404")
        return render(request,"province.html")


    def post(self,request,pname):
        concat = request.POST
        postBody = request.body
        tp = json.loads(postBody)
        global last_time
        last_time = get_datas.get_datas(last_time)
        pro_list, pro= data_area.objects.filter(count_id=pname).order_by("-total_confirm"),[]
        for obj in pro_list:
            pro.append(model_to_dict(obj))
        #print(pro)
        return http.JsonResponse(json.dumps({'pro': pro}))




class testmap(View):
    def get(self,request):
     return render(request,"test1.html")



class geti(View):
    def post(self,request,pname):
        concat = request.POST
        postBody = request.body
        tp = json.loads(postBody)

        b = data_province.objects.filter(count=pname)[0]
        tp['contry']=b.name
        a = data_area.objects.filter(count_id=b.count).order_by(tp['title'])
        p1,p2 = a.values_list('name'),a.values_list(tp['title'])
        p1 = [i[0] for i in p1]
        p2 = [i[0] for i in p2]
        aa,maxlen = [],len(p1)
        #慢
        for i in range(0,maxlen):
            aa.append([p1[i],p2[i]])
        #print(aa)
        data = {
            'code':200,
            'data':{
                'mp':province_map(aa,tp),
                'ba':china_bar(aa,tp),
                'pi':china_pie(aa,tp),
                'wc':china_wcd(aa,tp),
            },
            'msg':'OK',
        }
        print(data.data)
        return JsonResponse(json.dumps(data))
































# df = pd.DataFrame(pd.read_csv(r"C:\Users\asus\Desktop\covid\index\china_provincedata.csv"))
# for index,row in df.iterrows():
#     a = data_china.objects.filter(index = row['id'])
#     print(row['id'])
#     if not a:
#         ch = data_china(
#             #"id","confirmedCount","confirmedIncr","curedCount","curedIncr",
#             # "currentConfirmedCount","currentConfirmedIncr","dateId","deadCount",
#             # "deadIncr","suspectedCount","suspectedCountIncr","provinceName","provinceShortName"
#             index = row['id'],
#             total_confirm = row['confirmedCount'],
#             today_confirm = row['confirmedIncr'],
#             total_heal = row['curedCount'],
#             today_heal = row['curedIncr'],
#             total_nowconfirm = row['currentConfirmedCount'],
#             today_nowconfirm = row['currentConfirmedIncr'],
#             update_time = row['dateId'],
#             total_dead = row['deadCount'],
#             today_dead = row['deadIncr'],
#             total_suspect = row['suspectedCount'],
#             today_suspect = row['suspectedCountIncr'],
#             province_name = row['provinceName'],
#             province_short_name = row['provinceShortName'],
#         )
#         ch.save()